package connection.impl;

import config.ConnectionProperties;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class DbUtil implements connection.IDbUtil {

    @Autowired
    private ConnectionProperties properties;

    @Override
    @SneakyThrows
    public PreparedStatement getStat(String sql, Object... args) {
        Class.forName(properties.getDriverClass());
        Connection connection = DriverManager.getConnection(properties.getUrl(), properties.getUserName(), properties.getPassWord());
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < args.length; i++) {
            preparedStatement.setString(i + 1, (String) args[i]);
        }
        return preparedStatement;
    }
    @SneakyThrows
    @Override
    public void close(PreparedStatement preparedStatement) {
        Connection connection = preparedStatement.getConnection();
        preparedStatement.close();
        connection.close();
    }
}
